import { useEffect, useRef } from "react"
const { remote } = window.require('electron')

const { Menu, MenuItem } = remote

const useContextMenu = (itemArr: any, targetSelector: any) => {
    let clickedElement = useRef<React.ReactElement>()
    useEffect(() => {
        const handlecontextMenu = (e: any) => {
            let level = parseInt(e.target.getAttribute("data-level"))
            let menu: { append: (arg0: any) => void; popup: (arg0: { window: any }) => void } | null = null
            menu = new Menu()
            itemArr.forEach((item: any) => {
                item['visible'] = item.level.includes(level)
                if (menu !== null) {
                    menu.append(new MenuItem(item))
                }
            })
            // targetSelector
            if (document.querySelector(targetSelector).contains(e.target)) {

                clickedElement.current = e.target
                e.preventDefault()
                if (menu !== null) {
                    menu.popup({ window: remote.getCurrentWindow() })
                }
            }
        }
        window.addEventListener('contextmenu', handlecontextMenu, false)
        return () => {
            window.removeEventListener('contextmenu', handlecontextMenu)
        }
    })
    return (clickedElement as any)
}
export default useContextMenu